﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 用户管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.20
    /// </summary>
    internal class UserService : DataFactory, UserIService
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<UserEntity>> GetList(PageInput input)
        {
            using (var db = this.Basic)
            {
                var userId = UserProvider.Instance.Get().UserId;
                var queryWhere = ExtLinq.True<UserEntity>().And(m => m.IsAdministrator == 0).And(m => m.Id != userId);
                var queryParam = input.queryJson.ToObject();
                //组织机构
                if (!queryParam["organizeId"].IsEmpty())
                {
                    var index = 0;
                    var organizeIds = queryParam["organizeId"].ToString().Split(',');
                    foreach (var item in organizeIds)
                    {
                        queryWhere = index == 0 ? queryWhere.And(t => t.OrganizeId.Equals(item)) : queryWhere.Or(t => t.OrganizeId.Equals(item));
                        index++;
                    }
                }
                //关键字（账户、姓名、手机）
                if (!input.keyword.IsEmpty())
                {
                    queryWhere = queryWhere.And(m => m.Account.Contains(input.keyword) || m.RealName.Contains(input.keyword) || m.MobilePhone.Contains(input.keyword));
                }
                return await db.GetIQueryable<UserEntity>().Where(queryWhere).OrderBy(t => t.SortCode).GetPageResultAsync(input);
            }
        }


        /// <summary>
        /// 查询管家角色下面的用户
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetListByRoles()
        {
            try
            {

                //string role = "";
                //if (type == 1)
                //{
                string role1 = "4cbd3517c766476eb4751a6ab0511d53"; //信贷管家
                                                                   //}
                                                                   //else if (type == 2)
                                                                   //{
                string role2 = "860e2503441d4f01aeaf2efe5ab9b47e";
                //}
                //else if (type == 3)
                //{
                //资源回收
                string role3 = "2afef3a952c64145a6da90238ff49b97";
                //}
                using (var db = this.Basic)
                {
                    return await db.GetIQueryable<UserEntity>().Where(m => m.RoleId.Contains(role1) || m.RoleId.Contains(role2) || m.RoleId.Contains(role3)).Where(m => m.EnabledMark == 1).OrderBy(o => o.SortCode).ToListAsync();
                }
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error("错误：" + ex);
                throw new Exception(ex.Message);
            }
        }





        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetList()
        {
            try
            {
                using (var db = this.Basic)
                {
                    return await db.GetIQueryable<UserEntity>().OrderBy(o => o.SortCode).ToListAsync();
                }
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error("错误：" + ex);
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="positionId">岗位Id</param>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetListByPositionId(string positionId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<UserEntity>().Where(m => m.PositionId == positionId).OrderBy(o => o.SortCode).ToListAsync();
            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="managerId">主管Id</param>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetListByManagerId(string managerId)
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<UserEntity>().Where(m => m.ManagerId == managerId).OrderBy(o => o.SortCode).ToListAsync();
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<UserEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<UserEntity>(id);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="account">登录账户</param>
        /// <returns></returns>
        public async Task<UserEntity> GetInfoByAccount(string account)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<UserEntity>(m => m.Account == account || m.MobilePhone == account || m.Email == account);
            }
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns></returns>
        public async Task<bool> IsExist(Expression<Func<UserEntity, bool>> condition)
        {
            using (var db = this.Basic)
            {
                return await db.GetCountAsync(condition) > 0;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Delete(UserEntity entity)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();

                await db.DeleteAsync(entity);

                await db.DeleteAsync<UserRelationEntity>(m => m.UserId == entity.Id);

                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <param name="userRelationList">用户关系</param>
        /// <returns></returns>
        public async Task Create(UserEntity entity, List<UserRelationEntity> userRelationList)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();

                await db.InsertAsync(entity);

                await db.InsertAsync(userRelationList);

                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <param name="userRelationList">用户关系</param>
        /// <returns></returns>
        public async Task Update(UserEntity entity, List<UserRelationEntity> userRelationList)
        {
            var relationList = new List<UserRelationEntity>();
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();

                await db.UpdateAsync(entity);

                await db.DeleteAsync<UserRelationEntity>(m => m.UserId == entity.Id);

                await db.InsertAsync(userRelationList);

                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(UserEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }
    }
}
